<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<c:url value="/book/" var="bookUrl"/>
<c:url value="/profile/favorites/add" var="favoritesAddUrl"/>

<script type="text/javascript" >
function addPost(bookId) {
	var postText = $("#postText").val();

    $.post(
            "${bookUrl}" + bookId + "/addPost",
            {
                postText : postText
            }
    ).success(function(obj) {
        var text = obj.postText;
        var senderName = obj.postAuthor.firstName + " " + obj.postAuthor.lastName;

        console.info("text="+text);
        console.info("name="+ senderName);
        addRow(senderName,postText);

        $('#postText').val("");
    }).error(function(obj) {
        alert('Comment adding failed!');
    });
}

function addRow(sender,text) {
    $('#postTable tr:last').after("<tr><td>"+sender+"</td><td>"+text+"</td></tr>");
}

function addToFavorites(bookId) {
	$.post(
			"${favoritesAddUrl}",
            {
                bookId : bookId
            }
    ).success(function(obj) {
    	$('#info').html("Book has been successfully added to your Favorites list");
    }).error(function(obj) {
        alert('fail while adding the book');
    });
}
</script>



<h3 id="name">"${book.name}" book information (book's id: ${book.id})</h3>

<h4>Name ${book.name}</h4>
<h4>Release Date ${book.releaseDate}</h4>
<h4>Publisher ${book.publisher.name}</h4>
<c:if test="${not empty account}"><a href="#" onclick="addToFavorites(${book.id})">Add book to Favorites</a></c:if>
<div id="info"></div>
<br/><br/>

<table id="postTable" border="1" cellpadding="10" cellspacing="0" class="table table-striped table-bordered">
    <thead>
        <th>Sender</th>
        <th>Text</th>
    </thead>
    <tbody>
        <c:forEach items="${bookPosts}" var="post">
            <tr>
                <td>${post.postAuthor.firstName} ${post.postAuthor.lastName}</td>
                <td>${post.postText}</td>
            </tr>
        </c:forEach>
    </tbody>
</table>



<c:if test="${not empty account}">
    <textarea id="postText" placeholder="Your text" class="form-control" rows="8" cols="20"></textarea>
    <input type="submit" value="Post" class="btn btn-success" onclick="addPost(${book.id})"/>
</c:if>
<c:if test="${empty account}">
    <a href="<c:url value='/login' />">Log in</a> to send comment
</c:if>